package com.example.userspringboot.controller;

import com.example.userspringboot.common.Result;
import com.example.userspringboot.entity.DrugDetails;
import com.example.userspringboot.entity.Order;
import com.example.userspringboot.service.OrderService;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/orders")
public class OrderController {

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Resource
    OrderService orderService;

    @PostMapping("/createOrder")
    public Result createOrder(@RequestBody Map<String, Object> payload) {
        try {
            // 提取 order 字段并转换为 Order 对象
            Map<String, Object> orderMap = (Map<String, Object>) payload.get("order");
            Order order = objectMapper.convertValue(orderMap, Order.class);

            // 提取 drugDetails 字段并转换为 DrugDetails 对象
            Map<String, Object> drugDetailsMap = (Map<String, Object>) payload.get("drugDetails");
            DrugDetails drugDetails = objectMapper.convertValue(drugDetailsMap, DrugDetails.class);

            // 调用业务层
            orderService.createOrder(order, drugDetails);

            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("参数解析失败");
        }
    }

    @GetMapping("/selectOrdersById")
    public Result getOrderById(@RequestParam Integer userId) {
        List<Order> ordersList = orderService.getOrderById(userId);
        return Result.success(ordersList);
    }
}
